package com.rockcent.mall.controller;

import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.common.utils.DateFormatUtils;
import com.rockcent.common.utils.DateUtils;
import com.rockcent.mall.Routes;
import com.rockcent.mall.lib.domain.ChannelType;
import com.rockcent.mall.lib.domain.Merchant;
import com.rockcent.mall.lib.domain.enumclass.MerchantOrderSourceType;
import com.rockcent.mall.lib.domain.enumclass.ProductType;
import com.rockcent.mall.lib.domain.enumclass.StatististicsType;
import com.rockcent.mall.lib.dto.*;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.repository.*;
import com.rockcent.service.MerchantChannelStatisticsService;
import com.rockcent.service.MerchantProductStatisticsService;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by zhangjh on 2016/11/2.
 */
@RestController
public class MerchantChannelStatisticsController extends BaseController {


    private final Logger log = LoggerFactory.getLogger(MerchantChannelStatisticsController.class);

    @Autowired
    private BaseUserHelper userHelper;

    @Autowired
    private MerchantOrderRepository merchantOrderRepository;

    @Autowired
    private MerchantChannelRepository merchantChannelRepository;

    @Autowired
    private MerchantOrderVerificationRepository merchantOrderVerificationRepository;

    @Autowired
    private MerchantChannelStatisticsRepository merchantChannelStatisticsRepository;

    @Autowired
    private MerchantRepository merchantRepository;

    @Autowired
    private MerchantChannelStatisticsService merchantChannelStatisticsService;

    @Autowired
    private MerchantProductStatisticsService merchantProductStatisticsService;

    @Autowired
    private ChannelTypeRepository channelTypeRepository;

    /**
     *
     * @api {get} /merchant/channel/statistics B端 渠道统计
     * @apiGroup channel_statistics
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {String} type <code> 取值必须为  ALL("全部"), GOODS("商品"), SERVICE("服务")</code>   产品类型
     * @apiParam {Long} typeId  渠道类型ID
     * @apiParam {String}  sourceType <code>取值必须为 SELF("自营下单"), MARKET("分销下单")， ALL("全部")</code> 订单来源
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     * "code": "1",
     * "desc": "成功",
     * "data": {
     * "data": [
     * {
     *      "id": 1,
     *      "channelId": 6,
     *      "saleCount": 327,
     *      "verifyCount": 99,
     *      "viewCount": 10459,
     *      "clickCount": 872,
     *      "channelName": "默认平台渠道",
     *      "customerCount": 0,
     *      "orderConversionRate": "0%",
     *      "orderVerifiCationConversionRate": "0%",
     *      "productCategoryCount": 1
     * }
     * ....
     * ],
     *   "totalCount": 4830,
     *   "totalPage": 483,
     *   "pageNo": 0,
     *   "pageSize": 10,
     *   "url": "/merchant/channel/statistics",
     *   "prevUrl": "/merchant/channel/statistics?pageNo=0&pageSize=10",
     *   "nextUrl": "/merchant/channel/statistics?pageNo=1&pageSize=10"
     * }
     * }
     */
    @RequestMapping(value = Routes.MERCHANT_CHANNEL_STATISTICS, method = RequestMethod.GET)
    public JsonResult getChannelStatisticsInfo(MerchantChannelStatisticsDto merchantChannelStatisticsDto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);

        RestDoing doing = jsonResult -> {
            String type = merchantChannelStatisticsDto.getType();
            if (StringUtils.isBlank(type) || !EnumUtils.isValidEnum(ProductType.class, type)) {
                jsonResult.remind("type取值必须为  ALL(\"全部\"), GOODS(\"商品\"), SERVICE(\"服务\")", log);
                return;
            }
            String sourceType = merchantChannelStatisticsDto.getSourceType();
            if (StringUtils.isBlank(sourceType) || !EnumUtils.isValidEnum(MerchantOrderSourceType.class, sourceType)) {
                jsonResult.remind("sourceType 取值必须为 SELF(\"自营下单\"), MARKET(\"分销下单\")， ALL(\"全部\");", log);
                return;
            }

            //总订单数
            Long mallId = userInfoDto.mall.getId();
            Long merchantId = userInfoDto.merchant.getId();
            Long typeId = merchantChannelStatisticsDto.getTypeId();
            String startDate = merchantChannelStatisticsDto.getStartDate();
            String endDate = merchantChannelStatisticsDto.getEndDate();
            Long orderTotal = merchantOrderRepository.countMerchantOrderByMallIdAndMerchantId(mallId, merchantId, type, typeId, MerchantOrderSourceType.valueOf(sourceType), startDate, endDate);
            //总核销数
            Long verificationTotal = merchantOrderVerificationRepository.countMerchantOrderVerificationByMallIdAndMerchantId(mallId, merchantId, type, typeId, MerchantOrderSourceType.valueOf(sourceType), startDate, endDate);


            PageResult<MerchantChannelStatisticsDto> result = merchantChannelStatisticsRepository.getChannelStatisticsInfo(getPage(merchantChannelStatisticsDto.getPageNo(),merchantChannelStatisticsDto.getPageSize()), mallId, merchantId);

            result.data.forEach(statisticsDto -> {
                //下单数
              /* Long orderCount=merchantChannelStatisticsRepository.getOrderCountByChannelId(statisticsDto.getChannelId(), mallId, type, merchantId, typeId,  sourceType, startDate, endDate);
              if(orderCount==null){
                  orderCount=0l;
              }
                statisticsDto.setOrderCount(orderCount);*/
                if (orderTotal == null || orderTotal == 0) {
                    statisticsDto.setOrderConversionRate("0%");
                } else {
                    statisticsDto.setOrderConversionRate((statisticsDto.getOrderCount() == null ? 0 : statisticsDto.getOrderCount() / orderTotal) * 100 + "%");
                }
                if (verificationTotal == null || verificationTotal == 0) {
                    statisticsDto.setOrderVerifiCationConversionRate("0%");
                } else {
                    statisticsDto.setOrderVerifiCationConversionRate((statisticsDto.getVerifyCount() == null ? 0 : statisticsDto.getVerifyCount() / verificationTotal) * 100 + "%");
                }

                //TODO: 2016/12/5  产品数(要改)
                Long productCategoryCount = merchantChannelStatisticsRepository.getChannelProductCategoryCount(statisticsDto.getChannelId(), mallId, merchantId);
                if(productCategoryCount==null){
                    productCategoryCount=0l;
                }
                //下单人数
                Long customerCount = merchantOrderRepository.countMerchantOrderByChannelIdAndMallIdAndMerchantId(statisticsDto.getChannelId(), mallId, merchantId, type, typeId, MerchantOrderSourceType.valueOf(sourceType), startDate, endDate);
                //核销人数
                Long verificationCustomerCount = merchantOrderVerificationRepository.countMerchantCustomerVerificationByMallIdAndMerchantId(statisticsDto.getChannelId(), mallId, type, merchantId, typeId,  MerchantOrderSourceType.valueOf(sourceType), startDate, endDate);
                if(verificationCustomerCount==null){
                    verificationCustomerCount=0l;
                }
                //访问人数-未知统计口径
                Long viewCustomerCount=merchantChannelStatisticsRepository.getViewCountByChannelId(statisticsDto.getChannelId(), mallId, merchantId, type, typeId,  MerchantOrderSourceType.valueOf(sourceType), startDate, endDate);
                statisticsDto.setViewCount(viewCustomerCount==null?0:viewCustomerCount.intValue());
                statisticsDto.setCustomerCount(customerCount == null ? 0 : customerCount);
                statisticsDto.setVerificationCustomerCount(verificationCustomerCount == null ? 0 : verificationCustomerCount);
                statisticsDto.setProductCategoryCount(productCategoryCount == null ? 0 : productCategoryCount);
            });
            result.setUrl(Routes.MERCHANT_CHANNEL_STATISTICS);
            jsonResult.data = result;
        };
        return doing.go(request, log);
    }


    /**
     *
     * @api {get} /merchant/channel/product/statistics B端 渠道统计 明细
     * @apiGroup channel_statistics
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {Long} channelId  <code>必传参数</code> 渠道ID
     * @apiParam {String}  type    <code>取值必须为  ALL("全部"), GOODS("商品"), SERVICE("服务")</code>  商品类型
     * @apiParam {String} sourceType <code>取值必须为 ALL("全部"),  SELF("自营下单"), MARKET("分销下单")</code> 来源
     * @apiParam {String} startDate  <code>格式: yyyy-MM-dd</code> 开始日期
     * @apiParam {String} endDate     <code>格式: yyyy-MM-dd</code> 结束日期
     * @apiSuccessExample {json} Success-Response:
     * {
     *"code": "1",
     *"desc": "成功",
     *"data": {
     *  "data": [
     *  {
     *      "id": 272369,
     *      "productName": "饰品",
     *      "productId": 396,
     *      "saleCount": 11,
     *      "shareCount": 0,
     *      "verifyCount": 11,
     *      "orderCount": 0,
     *      "orderConversionRate": "0%",
     *      "orderVerifiCationConversionRate": "100%"
     *  }
     *  ...
     *  ],
     *      "totalCount": 894,
     *      "totalPage": 90,
     *      "pageNo": 0,
     *      "pageSize": 10,
     *      "url": "/merchant/channel/product/statistics",
     *      "prevUrl": "/merchant/channel/product/statistics?pageNo=0&pageSize=10",
     *      "nextUrl": "/merchant/channel/product/statistics?pageNo=1&pageSize=10"
     *}
     *}
     */
    @RequestMapping(value = Routes.MERCHANT_CHANNEL_PRODUCTS_STATISTICS, method = RequestMethod.GET)
    public JsonResult getChannelStatisticsDetails(MerchantChannelStatisticsDto merchantChannelStatisticsDto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            Long channelId = merchantChannelStatisticsDto.getChannelId();
            if (channelId == null) {
                jsonResult.remind("channelId 不能为空",log);
                return;
            }
            String type = merchantChannelStatisticsDto.getType();
            if (StringUtils.isBlank(type) || !EnumUtils.isValidEnum(ProductType.class, type)) {
                jsonResult.remind("type取值必须为  ALL(\"全部\"), GOODS(\"商品\"), SERVICE(\"服务\")", log);
                return;
            }
            String sourceType = merchantChannelStatisticsDto.getSourceType();
            if (StringUtils.isBlank(sourceType) || !EnumUtils.isValidEnum(MerchantOrderSourceType.class, sourceType)) {
                jsonResult.remind("sourceType 取值必须为    ALL(\"全部\"),  SELF(\"自营下单\"), MARKET(\"分销下单\");", log);
                return;
            }


            PageResult pageResult = this.getPage(merchantChannelStatisticsDto.getPageNo(), merchantChannelStatisticsDto.getPageSize());

            Long mallId = userInfoDto.mall.getId();
            Long merchantId = userInfoDto.merchant.getId();
            ChannelDto channelDto= merchantChannelRepository.getChannelById(channelId, merchantId, mallId, Whether.NO);
            if(channelDto!=null){
                merchantChannelStatisticsDto.setChannelName(channelDto.getName());
            }else{
                jsonResult.remind("加载渠道信息失败", log);
                return;
            }

            PageResult<ProductStatisticsDto> result = merchantChannelStatisticsRepository.getChannelProductStatisticsDetails(channelId, mallId, merchantId, type, MerchantOrderSourceType.valueOf(sourceType), merchantChannelStatisticsDto.getStartDate(), merchantChannelStatisticsDto.getEndDate(), merchantChannelStatisticsDto.getProductName(), pageResult);

            result.data.forEach(productStatisticsDto -> {


                Long productId = productStatisticsDto.getProductId();
                String startDate = merchantChannelStatisticsDto.getStartDate();
                String endDate = merchantChannelStatisticsDto.getEndDate();

                //访问次数
                Long viewCount= merchantChannelStatisticsRepository.getProductViewCount(productId, channelId, sourceType, type, mallId, merchantId, startDate, endDate);
                productStatisticsDto.setClickCount(viewCount);

                //访问人数
                Long viewCustomerCount= merchantChannelStatisticsRepository.getProductViewCustomerCount(productId, channelId, sourceType, type, mallId, merchantId, startDate, endDate);
                productStatisticsDto.setViewCount(viewCustomerCount);

                //销售数量
                Long saleCount= merchantChannelStatisticsRepository.getProductSaleCount(productId, channelId, sourceType, type, mallId, merchantId, startDate, endDate);
                productStatisticsDto.setSaleCount(saleCount);

                //下单人数
                Long customerCount = merchantChannelStatisticsRepository.getProductOrderCustomerCount(productId, channelId, sourceType, type, mallId, merchantId, startDate, endDate);

                //核销数量
                Long verificationCount =  merchantChannelStatisticsRepository.getProductVerifyCount(productId, channelId, sourceType, type, mallId, merchantId, startDate, endDate);
                productStatisticsDto.setVerifyCount(verificationCount);

                //核销人数
                Long verificationCustomerCount = merchantChannelStatisticsRepository.getProductVerifyCustomerCount(productId, channelId, sourceType, type, mallId, merchantId, startDate, endDate);

                //产品总下单数
                Long orderTotal = merchantChannelStatisticsRepository.getOrderTotalByProductIdAndMallIdAndMerchantId(productId, sourceType, type, mallId, merchantId, startDate, endDate);

                //产品总核销数
                Long verificationTotal = merchantChannelStatisticsRepository.getVerificationTotalByProductIdAndMallIdAndMerchantId(productId, sourceType, type, mallId, merchantId, startDate, endDate);


                Double price = merchantChannelStatisticsRepository.queryProductPriceByProductIdAndMallIdAndMerchantId(productId, channelId, sourceType, type, mallId, merchantId, startDate, endDate);

                productStatisticsDto.setCustomerCount(customerCount);
                productStatisticsDto.setPrice(price);

                productStatisticsDto.setVerificationCustomerCount(verificationCustomerCount);


                if (productStatisticsDto.getOrderCount()==null ||productStatisticsDto.getOrderCount() == 0) {
                    productStatisticsDto.setOrderConversionRate("0%");
                } else {
                    productStatisticsDto.setOrderConversionRate((productStatisticsDto.getOrderCount() / orderTotal) * 100 + "%");
                }
                if (verificationTotal==null||verificationTotal == 0) {
                    productStatisticsDto.setOrderVerifiCationConversionRate("0%");
                } else {
                    productStatisticsDto.setOrderVerifiCationConversionRate((productStatisticsDto.getVerifyCount() / verificationTotal) * 100 + "%");
                }
            });
            merchantChannelStatisticsDto.setProductStatisticsDtoPageResult(result);

            result.setUrl(Routes.MERCHANT_CHANNEL_PRODUCTS_STATISTICS);
            jsonResult.data = merchantChannelStatisticsDto;
        };

        return doing.go(request, log);
    }

    /**
     *
     * @api {get} /merchant/channel/statistics/chart B端 渠道统计 图表统计
     * @apiGroup channel_statistics
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {String}  statisticsType    <code>可为空 statisticsType 必须为 YESTERDAY("昨天"), WEEK("最近一周"), MONTH("最近一个月"), QUATER("最近三个月")</code>  商品类型
     * @apiParam {String} chartType <code>visit 访问情况  sale 销售情况  verification 核销情况</code> 图表类型
     * @apiParam {String} startDate  <code>格式: yyyy-MM-dd</code> 开始日期
     * @apiParam {String} endDate     <code>格式: yyyy-MM-dd</code> 结束日期
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功",
     *  "data": [
     *      {
     *           "dateCreated": "2016-10-09 09:58:39",
     *           "channelName": "默认平台渠道",
     *           "viewCustomer": 2
     *      },
     *      {
     *           "dateCreated": "2016-10-09 09:58:55",
     *           "channelName": "默认平台渠道",
     *           "viewCustomer": 2
     *      }...
     *]
     *}
     *
     *
     */
    @RequestMapping(value = Routes.MERCHANT_CHANNEL_STATISTICS_CHART, method = RequestMethod.GET)
    public JsonResult channelStatisticsChart(ChannelStatisticsChartDto channelStatisticsChartDto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);

        RestDoing doing = jsonResult -> {
            //下单量结果集
            List<ChannelStatisticsChartDto> saleCountResult = new ArrayList();
            //下单人数结果集
            List<ChannelStatisticsChartDto> orderCustomerCountResult = new ArrayList();
            //下单转化率结果集
            List<ChannelStatisticsChartDto> orderConversionRateResult = new ArrayList<ChannelStatisticsChartDto>();
            String chartType = channelStatisticsChartDto.getChartType();
            if (chartType == null) {
                jsonResult.remind(" chartType 不能为空，值必须为 visit 访问情况  sale 销售情况  verification 核销情况",log);
                return;
            }
            String statisticsType = channelStatisticsChartDto.getStatisticsType();
            Long typeId = channelStatisticsChartDto.getTypeId();
            Long merchantId = userInfoDto.merchant.getId();
            Long mallId = userInfoDto.mall.getId();
            String startDate = channelStatisticsChartDto.getStartDate();
            String endDate = channelStatisticsChartDto.getEndDate();
            if ("visit".equals(chartType)) {
                List<ChannelStatisticsChartDto> viewCountResult = new ArrayList<ChannelStatisticsChartDto>();
                List<ChannelStatisticsChartDto> customerCountResult = new ArrayList<ChannelStatisticsChartDto>();
                /**
                 *     /**
                 * 统计类型（昨天 YESTERDAY,近一周 WEEK,最近一个月 MONTH 最近三个月 QUATER）
                 */
                if (StringUtils.isNotBlank(statisticsType) && !EnumUtils.isValidEnum(StatististicsType.class, statisticsType)) {
                    jsonResult.remind("statisticsType 必须为 YESTERDAY(\"昨天\"), WEEK(\"最近一周\"), MONTH(\"最近一个月\"), QUATER(\"最近三个月\")",log);
                    return;
                } else if (StringUtils.isNotBlank(statisticsType)) {
                    customerCountResult = genarateCustomerCountChartByCondition(statisticsType, null, null, typeId, mallId, merchantId);
                    viewCountResult = genarateViewCountChartByCondition(statisticsType, null, null, typeId, mallId, merchantId);

                } else {
                    customerCountResult = genarateCustomerCountChartByCondition(statisticsType, startDate, endDate, typeId, mallId, merchantId);
                    viewCountResult = genarateViewCountChartByCondition(statisticsType, startDate, endDate, typeId, mallId, merchantId);
                }
                channelStatisticsChartDto.setViewCountResult(viewCountResult);
                channelStatisticsChartDto.setCustomerCountResult(customerCountResult);

                jsonResult.data = channelStatisticsChartDto;
            }
            if ("sale".equals(chartType)) {

                String type = channelStatisticsChartDto.getType();
                Long orderTotal = merchantOrderRepository.countMerchantOrderByMallIdAndMerchantId(mallId, merchantId, type, typeId,  MerchantOrderSourceType.ALL, startDate, endDate);
                /**
                 *
                 * 统计类型（昨天 YESTERDAY,近一周 WEEK,最近一个月 MONTH 最近三个月 QUATER）
                 */
                if (StringUtils.isNotBlank(statisticsType) && !EnumUtils.isValidEnum(StatististicsType.class, statisticsType)) {
                    jsonResult.remind("statisticsType 必须为 YESTERDAY(\"昨天\"), WEEK(\"最近一周\"), MONTH(\"最近一个月\"), QUATER(\"最近三个月\")",log);
                    return;
                } else if (StringUtils.isNotBlank(statisticsType)) {
                    saleCountResult = genarateSaleCountChartByCondition(statisticsType, null, null, mallId, merchantId);
                    orderCustomerCountResult = genarateSaleCustomerCountChartByCondition(statisticsType, null, null, mallId, merchantId);
                    orderConversionRateResult = genarateSaleRateChartByCondition(statisticsType, null, null, mallId, merchantId);


                } else {
                    saleCountResult = genarateSaleCountChartByCondition(statisticsType, startDate, endDate, mallId, merchantId);
                    orderCustomerCountResult = genarateSaleCustomerCountChartByCondition(statisticsType, startDate, endDate, mallId, merchantId);
                    orderConversionRateResult = genarateSaleRateChartByCondition(statisticsType, startDate, endDate, mallId, merchantId);
                }
                channelStatisticsChartDto.setSaleCountResult(saleCountResult);
                channelStatisticsChartDto.setOrderCustomerCountResult(orderCustomerCountResult);
                channelStatisticsChartDto.setOrderConversionRateResult(orderConversionRateResult);
                jsonResult.data = channelStatisticsChartDto;
            }
            if ("verification".equals(chartType)) {
                //核销量结果集
                List verificationCountResult = new ArrayList();
                //核销人数结果集
                List verificationCustomerCountResult = new ArrayList();
                //核销转化率结果集
                List verificationConversionRateResult = new ArrayList();
                /**
                 *     /**
                 * 统计类型（昨天 YESTERDAY,近一周 WEEK,最近一个月 MONTH 最近三个月 QUATER）
                 */
                if (StringUtils.isNotBlank(statisticsType) && !EnumUtils.isValidEnum(StatististicsType.class, statisticsType)) {
                    jsonResult.remind("statisticsType 必须为 YESTERDAY(\"昨天\"), WEEK(\"最近一周\"), MONTH(\"最近一个月\"), QUATER(\"最近三个月\")",log);
                    return;
                } else if (StringUtils.isNotBlank(statisticsType)) {
                    verificationCountResult = genarateVerificationCountChartByCondition(statisticsType, null, null, mallId, merchantId);
                    verificationCustomerCountResult = genarateVerificationCustomerCountChartByCondition(statisticsType, null, null, mallId, merchantId);
                    verificationConversionRateResult = genarateVerificationRateChartByCondition(statisticsType, null, null, mallId, merchantId);

                } else {
                    verificationCountResult = genarateVerificationCountChartByCondition(statisticsType, startDate, endDate, mallId, merchantId);
                    verificationCustomerCountResult = genarateVerificationCustomerCountChartByCondition(statisticsType, startDate, endDate, mallId, merchantId);
                    verificationConversionRateResult = genarateVerificationRateChartByCondition(statisticsType, startDate, endDate, mallId, merchantId);
                }
                channelStatisticsChartDto.setVerificationCountResult(verificationCountResult);
                channelStatisticsChartDto.setVerificationCustomerCountResult(verificationCustomerCountResult);
                channelStatisticsChartDto.setVerificationConversionRateResult(verificationConversionRateResult);

                jsonResult.data = channelStatisticsChartDto;
            }

        };
        return doing.go(request, log);

    }

    /**
     * 生成核销转化率统计图数据集
     * @param statisticsType
     * @param startDate
     * @param endDate
     * @param mallId
     * @param merchantId
     * @return
     */
    private List genarateVerificationRateChartByCondition(String statisticsType, String startDate, String endDate, Long mallId, Long merchantId) {
        //昨天
        if (statisticsType != null) {
            if (StatististicsType.YESTERDAY == StatististicsType.valueOf(statisticsType)) {

                List result = merchantChannelStatisticsRepository.genarateVerificationRateChartByCondition(null, null, mallId, merchantId, StatististicsType.YESTERDAY);
//                //log.info(result.toString());
                return result;
            }
            //每周
            if (StatististicsType.WEEK == StatististicsType.valueOf(statisticsType)) {

                List result = merchantChannelStatisticsRepository.genarateVerificationRateChartByCondition(null, null, mallId, merchantId, StatististicsType.WEEK);
                return result;
            }
            //近一个月
            if (StatististicsType.MONTH == StatististicsType.valueOf(statisticsType)) {

                List result = merchantChannelStatisticsRepository.genarateVerificationRateChartByCondition(null, null, mallId, merchantId, StatististicsType.MONTH);
                return result;
            }
            if (StatististicsType.QUATER == StatististicsType.valueOf(statisticsType)) {
                //每个季度
                List result = merchantChannelStatisticsRepository.genarateVerificationRateChartByCondition(null, null, mallId, merchantId, StatististicsType.QUATER);
                return result;
            }
        } else {
            List result = merchantChannelStatisticsRepository.genarateVerificationRateChartByCondition(startDate, endDate, mallId, merchantId, null);
            return result;
        }
        return null;
    }

    /**
     * 生成核销人数统计图数据集
     * @param statisticsType
     * @param startDate
     * @param endDate
     * @param mallId
     * @param merchantId
     * @return
     */
    private List genarateVerificationCustomerCountChartByCondition(String statisticsType, String startDate, String endDate, Long mallId, Long merchantId) {
        //昨天
        if (statisticsType != null) {
            if (StatististicsType.YESTERDAY == StatististicsType.valueOf(statisticsType)) {

                List result = merchantChannelStatisticsRepository.genarateVerificationCustomerCountChartByCondition(null, null, mallId, merchantId, StatististicsType.YESTERDAY);
                //log.info(result.toString());
                return result;
            }
            //每周
            if (StatististicsType.WEEK == StatististicsType.valueOf(statisticsType)) {

                List result = merchantChannelStatisticsRepository.genarateVerificationCustomerCountChartByCondition(null, null, mallId, merchantId, StatististicsType.WEEK);
                return result;
            }
            //近一个月
            if (StatististicsType.MONTH == StatististicsType.valueOf(statisticsType)) {

                List result = merchantChannelStatisticsRepository.genarateVerificationCustomerCountChartByCondition(null, null, mallId, merchantId, StatististicsType.MONTH);
                return result;
            }
            if (StatististicsType.QUATER == StatististicsType.valueOf(statisticsType)) {
                //每个季度
                List result = merchantChannelStatisticsRepository.genarateVerificationCustomerCountChartByCondition(null, null, mallId, merchantId, StatististicsType.QUATER);
                return result;
            }
        } else {
            List result = merchantChannelStatisticsRepository.genarateVerificationCustomerCountChartByCondition(startDate, endDate, mallId, merchantId, null);
            return result;
        }
        return null;
    }

    /**
     * 生成核销数统计图数据集
     * @param statisticsType
     * @param startDate
     * @param endDate
     * @param mallId
     * @param merchantId
     * @return
     */
    private List genarateVerificationCountChartByCondition(String statisticsType, String startDate, String endDate, Long mallId, Long merchantId) {
        //昨天
        if (statisticsType != null) {
            if (StatististicsType.YESTERDAY == StatististicsType.valueOf(statisticsType)) {

                List result = merchantChannelStatisticsRepository.genarateVerificationCountChartByCondition(startDate, endDate, mallId, merchantId, StatististicsType.YESTERDAY);
                //log.info(result.toString());
                return result;
            }
            //每周
            if (StatististicsType.WEEK == StatististicsType.valueOf(statisticsType)) {

                List result = merchantChannelStatisticsRepository.genarateVerificationCountChartByCondition(startDate, endDate, mallId, merchantId, StatististicsType.WEEK);
                return result;
            }
            //近一个月
            if (StatististicsType.MONTH == StatististicsType.valueOf(statisticsType)) {

                List result = merchantChannelStatisticsRepository.genarateVerificationCountChartByCondition(startDate, endDate, mallId, merchantId, StatististicsType.MONTH);
                return result;
            }
            if (StatististicsType.QUATER == StatististicsType.valueOf(statisticsType)) {
                //每个季度
                List result = merchantChannelStatisticsRepository.genarateVerificationCountChartByCondition(startDate, endDate, mallId, merchantId, StatististicsType.QUATER);
                return result;
            }
        } else {
            List result = merchantChannelStatisticsRepository.genarateVerificationCountChartByCondition(startDate, endDate, mallId, merchantId, null);
            return result;
        }
        return null;
    }

    /**
     *  下单转化率统计图数据集
     * @param statisticsType
     * @param startDate
     * @param endDate
     * @param mallId
     * @param merchantId
     * @return
     */
    private List genarateSaleRateChartByCondition(String statisticsType, String startDate, String endDate, Long mallId, Long merchantId) {
        //昨天
        if (statisticsType != null) {
            if (StatististicsType.YESTERDAY == StatististicsType.valueOf(statisticsType)) {

                List result = merchantChannelStatisticsRepository.genarateSaleRateChartByCondition(startDate, endDate, mallId, merchantId, StatististicsType.YESTERDAY);
                //log.info(result.toString());
                return result;
            }
            //每周
            if (StatististicsType.WEEK == StatististicsType.valueOf(statisticsType)) {

                List result = merchantChannelStatisticsRepository.genarateSaleRateChartByCondition(startDate, endDate, mallId, merchantId, StatististicsType.WEEK);
                return result;
            }
            //近一个月
            if (StatististicsType.MONTH == StatististicsType.valueOf(statisticsType)) {

                List result = merchantChannelStatisticsRepository.genarateSaleRateChartByCondition(startDate, endDate, mallId, merchantId, StatististicsType.MONTH);
                return result;
            }
            if (StatististicsType.QUATER == StatististicsType.valueOf(statisticsType)) {
                //每个季度
                List result = merchantChannelStatisticsRepository.genarateSaleRateChartByCondition(startDate, endDate, mallId, merchantId, StatististicsType.QUATER);
                return result;
            }
        } else {
            List result = merchantChannelStatisticsRepository.genarateSaleRateChartByCondition(startDate, endDate, mallId, merchantId, null);
            return result;
        }
        return null;
    }


    /**
     * 下单人数结果集统计图
     * @param statisticsType
     * @param startDate
     * @param endDate
     * @param mallId
     * @param merchantId
     * @return
     */
    private List genarateSaleCustomerCountChartByCondition(String statisticsType, String startDate, String endDate, Long mallId, Long merchantId) {

        //昨天
        if (statisticsType != null) {
            if (StatististicsType.YESTERDAY == StatististicsType.valueOf(statisticsType)) {

                List result = merchantChannelStatisticsRepository.genarateSaleCustomerCountChartByCondition(startDate, endDate, mallId, merchantId, StatististicsType.YESTERDAY);
                //log.info(result.toString());
                return result;
            }
            //每周
            if (StatististicsType.WEEK == StatististicsType.valueOf(statisticsType)) {

                List result = merchantChannelStatisticsRepository.genarateSaleCustomerCountChartByCondition(startDate, endDate, mallId, merchantId, StatististicsType.WEEK);
                return result;
            }
            //近一个月
            if (StatististicsType.MONTH == StatististicsType.valueOf(statisticsType)) {

                List result = merchantChannelStatisticsRepository.genarateSaleCustomerCountChartByCondition(startDate, endDate, mallId, merchantId, StatististicsType.MONTH);
                return result;
            }
            if (StatististicsType.QUATER == StatististicsType.valueOf(statisticsType)) {
                //每个季度
                List result = merchantChannelStatisticsRepository.genarateSaleCustomerCountChartByCondition(startDate, endDate, mallId, merchantId, StatististicsType.QUATER);
                return result;
            }
        } else {
            List result = merchantChannelStatisticsRepository.genarateSaleCustomerCountChartByCondition(startDate, endDate, mallId, merchantId, null);
            return result;
        }
        return null;
    }

    /**
     * 销售数结果集统计图
     * @param statisticsType
     * @param startDate
     * @param endDate
     * @param mallId
     * @param merchantId
     * @return
     */
    private List genarateSaleCountChartByCondition(String statisticsType, String startDate, String endDate, Long mallId, Long merchantId) {
        //昨天
        if (statisticsType != null) {
            if (StatististicsType.YESTERDAY == StatististicsType.valueOf(statisticsType)) {

                List result = merchantChannelStatisticsRepository.genarateSaleCountChartByCondition(startDate, endDate, mallId, merchantId, StatististicsType.YESTERDAY);
                //log.info(result.toString());
                return result;
            }
            //每周
            if (StatististicsType.WEEK == StatististicsType.valueOf(statisticsType)) {

                List result = merchantChannelStatisticsRepository.genarateSaleCountChartByCondition(startDate, endDate, mallId, merchantId, StatististicsType.WEEK);
                return result;
            }
            //近一个月
            if (StatististicsType.MONTH == StatististicsType.valueOf(statisticsType)) {

                List result = merchantChannelStatisticsRepository.genarateSaleCountChartByCondition(startDate, endDate, mallId, merchantId, StatististicsType.MONTH);
                return result;
            }
            if (StatististicsType.QUATER == StatististicsType.valueOf(statisticsType)) {
                //每个季度
                List result = merchantChannelStatisticsRepository.genarateSaleCountChartByCondition(startDate, endDate, mallId, merchantId, StatististicsType.QUATER);
                return result;
            }
        } else {
            List result = merchantChannelStatisticsRepository.genarateSaleCountChartByCondition(startDate, endDate, mallId, merchantId, null);
            return result;
        }
        return null;
    }

    /**
     *  访问数统计图
     * @param statisticsType
     * @param startDate
     * @param endDate
     * @param typeId
     *@param mallId
     * @param merchantId   @return
     */
    private List<ChannelStatisticsChartDto> genarateViewCountChartByCondition(String statisticsType, String startDate, String endDate, Long typeId, Long mallId, Long merchantId) {

        //昨天
        if (statisticsType != null) {
            if (StatististicsType.YESTERDAY == StatististicsType.valueOf(statisticsType)) {

                List<ChannelStatisticsChartDto> result = merchantChannelStatisticsRepository.genarateViewCountChartByCondition(startDate, endDate, mallId, merchantId, StatististicsType.YESTERDAY);
                //log.info(result.toString());
                return result;
            }
            //每周
            if (StatististicsType.WEEK == StatististicsType.valueOf(statisticsType)) {

                List<ChannelStatisticsChartDto> result = merchantChannelStatisticsRepository.genarateViewCountChartByCondition(null, null, mallId, merchantId, StatististicsType.WEEK);
                return result;
            }
            //近一个月
            if (StatististicsType.MONTH == StatististicsType.valueOf(statisticsType)) {

                List<ChannelStatisticsChartDto> result = merchantChannelStatisticsRepository.genarateViewCountChartByCondition(null, null, mallId, merchantId, StatististicsType.MONTH);
                return result;
            }
            if (StatististicsType.QUATER == StatististicsType.valueOf(statisticsType)) {
                //每个季度
                List<ChannelStatisticsChartDto> result = merchantChannelStatisticsRepository.genarateViewCountChartByCondition(null, null, mallId, merchantId, StatististicsType.QUATER);
                return result;
            }
        } else {
            List<ChannelStatisticsChartDto> result = merchantChannelStatisticsRepository.genarateViewCountChartByCondition(startDate, endDate, mallId, merchantId, null);
            return result;
        }
        return null;

    }


    /**
     * 访问人数统计图
     * @param type
     * @param startDate
     * @param endDate
     * @param typeId
     *@param mallId
     * @param merchantId   @return
     */
    private List<ChannelStatisticsChartDto> genarateCustomerCountChartByCondition(String type, String startDate, String endDate, Long typeId, Long mallId, Long merchantId) {

        //昨天
        if (type != null) {
            if (StatististicsType.YESTERDAY == StatististicsType.valueOf(type)) {

                List<ChannelStatisticsChartDto> result = merchantChannelStatisticsRepository.genarateCustomerCountChartByCondition(null, null, mallId, merchantId, StatististicsType.YESTERDAY);
                //log.info(result.toString());
                return result;
            }
            //每周
            if (StatististicsType.WEEK == StatististicsType.valueOf(type)) {

                List<ChannelStatisticsChartDto> result = merchantChannelStatisticsRepository.genarateCustomerCountChartByCondition(null, null, mallId, merchantId, StatististicsType.WEEK);
                return result;
            }
            //近一个月
            if (StatististicsType.MONTH == StatististicsType.valueOf(type)) {

                List<ChannelStatisticsChartDto> result = merchantChannelStatisticsRepository.genarateCustomerCountChartByCondition(null, null, mallId, merchantId, StatististicsType.MONTH);
                return result;
            }
            if (StatististicsType.QUATER == StatististicsType.valueOf(type)) {
                //每个季度
                List<ChannelStatisticsChartDto> result = merchantChannelStatisticsRepository.genarateCustomerCountChartByCondition(null, null, mallId, merchantId, StatististicsType.QUATER);
                return result;
            }
        } else {
            List<ChannelStatisticsChartDto> result = merchantChannelStatisticsRepository.genarateCustomerCountChartByCondition(startDate, endDate, mallId, merchantId, null);
            return result;
        }
        return null;
    }

    /**
     * @api {get} merchant/channel/statistics/query/chart 渠道趋势图
     * @apiGroup B端 merchant channel statistics
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {String} startDate 开始时间
     * @apiParam {String} endDate 结束时间
     * @apiParam {String} statisticsType YESTERDAY("昨天"), WEEK("最近一周"), MONTH("最近一个月"), QUATER("最近三个月")
     * @apiParam {Long} typeId 渠道类型ID
     * @apiParam {String} chartType visit 访问情况 sale 销售情况 verification 核销情况 图表类型
     *
     * @apiSuccess {String} dateStr 日期
     * @apiSuccess {String} channelName 渠道名称
     * @apiSuccess {Long} viewCount 访问次数
     * @apiSuccess {Long} viewCustomer 访问人数
     * @apiSuccess {Long} saleCount 售出数
     * @apiSuccess {Long} saleCustomerCount 下单人数
     * @apiSuccess {Double} saleConversionRate 下单转化率
     * @apiSuccess {Long} verificationCount 核销数量
     * @apiSuccess {Long} verificationCustomerCount 核销人数
     * @apiSuccess {Double} verificationRate 核销转化率
     * @apiSuccess {List} viewCountResult 访问次数结果集
     * @apiSuccess {List} customerCountResult 访客人数结果集
     * @apiSuccess {List} saleCountResult 售出数量结果集
     * @apiSuccess {List} orderCustomerCountResult 下单人数结果集
     * @apiSuccess {List} orderConversionRateResult 下单转化率结果集
     * @apiSuccess {List} verificationCustomerCountResult 核销人数结果集
     * @apiSuccess {List} verificationCountResult 核销数量结果集
     * @apiSuccess {List} verificationConversionRateResult 核销转化率结果集
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *     "saleCountResult": [
     *       {
     *         "id": 132,
     *         "channelName": "渠道订单统计",
     *         "dateStr": "2017/01/17",
     *         "viewCount": 0,
     *         "saleCount": 1,
     *         "saleCustomerCount": 0,
     *         "verificationCustomerCount": 0,
     *         "verificationCount": 0,
     *         "verificationRate": 0,
     *         "saleConversionRate": 0,
     *         "viewCustomer": 0
     *       }
     *     ],
     *     "orderCustomerCountResult": [
     *       {
     *         "id": 131,
     *         "channelName": "花茶渠道",
     *         "dateStr": "2017/01/17",
     *         "viewCount": 0,
     *         "saleCount": 0,
     *         "saleCustomerCount": 1,
     *         "verificationCustomerCount": 0,
     *         "verificationCount": 0,
     *         "verificationRate": 0,
     *         "saleConversionRate": 0,
     *         "viewCustomer": 0
     *       }
     *     ],
     *     "orderConversionRateResult": [
     *       {
     *         "channelName": "渠道订单统计",
     *         "dateStr": "2017/01/16",
     *         "viewCount": 0,
     *         "saleCount": 0,
     *         "saleCustomerCount": 0,
     *         "verificationCustomerCount": 0,
     *         "verificationCount": 0,
     *         "verificationRate": 0,
     *         "saleConversionRate": 0,
     *         "viewCustomer": 0
     *       }
     *     ]
     *   }
     * }
     */
    @RequestMapping(value = Routes.MERCHANT_CHANNEL_STATISTICS_QUERY_CHART, method = RequestMethod.GET)
    public JsonResult channelStatisticsQueryChart(ChannelStatisticsChartDto channelStatisticsChartDto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            String chartType = channelStatisticsChartDto.getChartType();
            if(chartType==null) {
                jsonResult.remind("chartType 不能为空",log);
                return;
            }
            if (!(chartType.equals("visit") || chartType.equals("sale") || chartType.equals("verification"))) {
                jsonResult.remind(" chartType值必须为 visit 访问情况  sale 销售情况  verification 核销情况",log);
                return;
            }
            if(!checkDto(channelStatisticsChartDto,jsonResult)) {
                return;
            }
            Long mallId = userInfoDto.mall.getId();
            Long merchantId = userInfoDto.merchant.getId();
            String startDate = channelStatisticsChartDto.getStartDate();
            String endDate = channelStatisticsChartDto.getEndDate();
            List<Long> typeIdList = channelStatisticsChartDto.getTypeIds();
            String groupByType = channelStatisticsChartDto.getGroupByType();
            List<Long> typeIds = null;
            if(typeIdList!=null && typeIdList.size()>0) {
                typeIds = new ArrayList<>();
                typeIds.addAll(typeIdList);
            }
            ChannelStatisticsChartDto chartDto = new ChannelStatisticsChartDto();
            //访问次数
            List<ChannelStatisticsChartDto> viewCountResult = new ArrayList<>();
            //访问人数
            List<ChannelStatisticsChartDto> customerCountResult = new ArrayList<>();
            //下单量结果集
            List<ChannelStatisticsChartDto> saleCountResult = new ArrayList();
            //下单人数结果集
            List<ChannelStatisticsChartDto> orderCustomerCountResult = new ArrayList();
            //下单转化率结果集
            List<ChannelStatisticsChartDto> orderConversionRateResult = new ArrayList<>();
            //核销量结果集
            List<ChannelStatisticsChartDto> verificationCountResult = new ArrayList();
            //核销人数结果集
            List<ChannelStatisticsChartDto> verificationCustomerCountResult = new ArrayList();
            //核销转化率结果集
            List<ChannelStatisticsChartDto> verificationConversionRateResult = new ArrayList();
            if("visit".equals(channelStatisticsChartDto.getChartType())) {
                //获取访问次数前10的渠道列表
                List<ChannelStatisticsChartDto> viewCountChannels = merchantChannelStatisticsService.channelViewCount(mallId,merchantId,startDate,endDate,typeIds,null,"other",null);
                if(viewCountChannels!=null && viewCountChannels.size()>0) {
                    //初始化渠道数据
                    List<ChannelStatisticsChartDto> viewCountInit=init(groupByType,viewCountChannels,startDate,endDate);
                    List<ChannelStatisticsChartDto> viewCountRet=merchantChannelStatisticsService.channelViewCount(mallId,merchantId,startDate,endDate,typeIds,null,groupByType,getChannelIds(viewCountChannels));
                    viewCountResult.addAll(resetStatisticsChart("viewCount",viewCountInit,viewCountRet));
                }
                //获取访问人数前10的渠道列表
                List<ChannelStatisticsChartDto> viewCustomerCountChannels = merchantChannelStatisticsService.channelViewCustomerCount(mallId,merchantId,startDate,endDate,typeIds,null,"other",null);
                if(viewCustomerCountChannels!=null && viewCustomerCountChannels.size()>0) {
                    //初始化渠道数据
                    List<ChannelStatisticsChartDto> customerCountInit=init(groupByType,viewCountChannels,startDate,endDate);
                    List<ChannelStatisticsChartDto> customerCountRet=merchantChannelStatisticsService.channelViewCustomerCount(mallId,merchantId,startDate,endDate,typeIds,null,groupByType,getChannelIds(viewCustomerCountChannels));
                    customerCountResult.addAll(resetStatisticsChart("viewCustomer",customerCountInit,customerCountRet));
                }
                chartDto.setViewCountResult(viewCountResult);
                chartDto.setCustomerCountResult(customerCountResult);
            } else if("sale".equals(channelStatisticsChartDto.getChartType())) {
                //获取访问人数前10的渠道列表
                List<ChannelStatisticsChartDto> viewCustomerCountChannels = merchantChannelStatisticsService.channelViewCustomerCount(mallId,merchantId,startDate,endDate,typeIds,null,"other",null);
                List<ChannelStatisticsChartDto> viewCustomerCountList = new ArrayList<>();
                if(viewCustomerCountChannels!=null && viewCustomerCountChannels.size()>0) {
                    viewCustomerCountList = merchantChannelStatisticsService.channelViewCustomerCount(mallId,merchantId,startDate,endDate,typeIds,null,groupByType,getChannelIds(viewCustomerCountChannels));
                }
                //获取下单量前10的渠道列表
                List<ChannelStatisticsChartDto> saleCountChannels = merchantChannelStatisticsService.channelSaleCount(mallId,merchantId,startDate,endDate,typeIds,null,"other",null);
                if(saleCountChannels!=null && saleCountChannels.size()>0) {
                    //初始化渠道数据
                    List<ChannelStatisticsChartDto> saleCountInit=init(groupByType,saleCountChannels,startDate,endDate);
                    List<ChannelStatisticsChartDto> saleCountRet=merchantChannelStatisticsService.channelSaleCount(mallId,merchantId,startDate,endDate,typeIds,null,groupByType,getChannelIds(saleCountChannels));
                    saleCountResult.addAll(resetStatisticsChart("saleCount",saleCountInit,saleCountRet));
                }
                //获取下单人数前10的渠道列表
                List<ChannelStatisticsChartDto> orderCustomerCountChannels = merchantChannelStatisticsService.channelOrderCustomerCount(mallId,merchantId,startDate,endDate,typeIds,null,"other",null);
                if(orderCustomerCountChannels!=null && orderCustomerCountChannels.size()>0) {
                    //初始化渠道数据
                    List<ChannelStatisticsChartDto> orderCustomerCountInit=init(groupByType,orderCustomerCountChannels,startDate,endDate);
                    List<ChannelStatisticsChartDto> orderCustomerCountList = merchantChannelStatisticsService.channelOrderCustomerCount(mallId,merchantId,startDate,endDate,typeIds,null,groupByType,getChannelIds(orderCustomerCountChannels));
                    chartDto.setViewCountResult(orderCustomerCountList);
                    orderCustomerCountResult.addAll(resetStatisticsChart("saleCustomerCount",orderCustomerCountInit,orderCustomerCountList));
                    List<ChannelStatisticsChartDto> orderConversionRateInit=init(groupByType,orderCustomerCountChannels,startDate,endDate);
                    orderConversionRateResult.addAll(resetStatisticsChart("saleConversionRate",orderConversionRateInit,calConversionRate(orderCustomerCountList,viewCustomerCountList,"sale")));
                }
                chartDto.setSaleCountResult(saleCountResult);
                chartDto.setOrderCustomerCountResult(orderCustomerCountResult);
                chartDto.setOrderConversionRateResult(orderConversionRateResult);
            } else if("verification".equals(channelStatisticsChartDto.getChartType())) {
                //获取下单量前10的渠道列表
                List<ChannelStatisticsChartDto> saleCountChannels = merchantChannelStatisticsService.channelSaleCount(mallId,merchantId,startDate,endDate,typeIds,null,"other",null);
                List<ChannelStatisticsChartDto> saleCountList = new ArrayList<>();
                if(saleCountChannels!=null && saleCountChannels.size()>0) {
                    saleCountList=merchantChannelStatisticsService.channelSaleCount(mallId,merchantId,startDate,endDate,typeIds,null,groupByType,getChannelIds(saleCountChannels));
                }
                //获取核销量前10的渠道列表
                List<ChannelStatisticsChartDto> verificationCountChannels = merchantChannelStatisticsService.channelVerifyCount(mallId,merchantId,startDate,endDate,typeIds,null,"other",null);
                if(verificationCountChannels!=null && verificationCountChannels.size()>0) {
                    //初始化渠道数据
                    List<ChannelStatisticsChartDto> verificationCountInit=init(groupByType,verificationCountChannels,startDate,endDate);
                    List<ChannelStatisticsChartDto> verificationCountRet=merchantChannelStatisticsService.channelVerifyCount(mallId,merchantId,startDate,endDate,typeIds,null,groupByType,getChannelIds(verificationCountChannels));
                    verificationCountResult.addAll(resetStatisticsChart("verificationCount",verificationCountInit,verificationCountRet));

                    //初始化渠道数据
                    List<ChannelStatisticsChartDto> verificationConversionRateInit=init(groupByType,verificationCountChannels,startDate,endDate);
                    verificationConversionRateResult.addAll(resetStatisticsChart("verificationRate",verificationConversionRateInit,calConversionRate(verificationCountRet,saleCountList,"verification")));
                }
                //获取核销人数前10的渠道列表
                List<ChannelStatisticsChartDto> verificationCustomerCountChannels = merchantChannelStatisticsService.channelVerifyCustomerCount(mallId,merchantId,startDate,endDate,typeIds,null,"other",null);
                if(verificationCustomerCountChannels!=null && verificationCustomerCountChannels.size()>0) {
                    //初始化渠道数据
                    List<ChannelStatisticsChartDto> verificationCustomerInit=init(groupByType,verificationCustomerCountChannels,startDate,endDate);
                    List<ChannelStatisticsChartDto> verificationCustomerList = merchantChannelStatisticsService.channelVerifyCustomerCount(mallId,merchantId,startDate,endDate,typeIds,null,groupByType,getChannelIds(verificationCustomerCountChannels));
                    verificationCustomerCountResult.addAll(resetStatisticsChart("verificationCustomerCount",verificationCustomerInit,verificationCustomerList));
                }
                chartDto.setVerificationCountResult(verificationCountResult);
                chartDto.setVerificationCustomerCountResult(verificationCustomerCountResult);
                chartDto.setVerificationConversionRateResult(verificationConversionRateResult);
            }
            jsonResult.data = chartDto;
        };
        return doing.go(request, log);
    }

    /**
     * 重设统计数据
     * @param dtoList
     * @param statisticsDtoList
     */
    private List<ChannelStatisticsChartDto> resetStatisticsChart(String key, List<ChannelStatisticsChartDto> dtoList,List<ChannelStatisticsChartDto> statisticsDtoList) {
        if(statisticsDtoList==null || statisticsDtoList.size()==0 || dtoList==null || dtoList.size()==0) {
            return dtoList;
        }
        for(ChannelStatisticsChartDto dto : dtoList) {
            ChannelStatisticsChartDto statisticsDto = findDtoByDate(dto.getDateStr()+"-"+dto.getId(),statisticsDtoList);
            if(statisticsDto!=null) {
                if(key.equals("viewCount")) {
                    dto.setViewCount(statisticsDto.getViewCount());
                } else if(key.equals("viewCustomer")) {
                    dto.setViewCustomer(statisticsDto.getViewCustomer());
                } else if(key.equals("saleCount")) {
                    dto.setSaleCount(statisticsDto.getSaleCount());
                } else if(key.equals("saleCustomerCount")) {
                    dto.setSaleCustomerCount(statisticsDto.getSaleCustomerCount());
                } else if(key.equals("saleConversionRate")) {
                    dto.setSaleConversionRate(statisticsDto.getSaleConversionRate());
                } else if(key.equals("verificationCount")) {
                    dto.setVerificationCount(statisticsDto.getVerificationCount());
                } else if(key.equals("verificationCustomerCount")) {
                    dto.setVerificationCustomerCount(statisticsDto.getVerificationCustomerCount());
                } else if(key.equals("verificationRate")) {
                    dto.setVerificationRate(statisticsDto.getVerificationRate());
                }
            }
        }
        return dtoList;
    }

    /**
     * 通过渠道ID与日期初始化数据
     * @param channels
     * @param startDate
     * @param endDate
     */
    private List<ChannelStatisticsChartDto> init(String groupByType, List<ChannelStatisticsChartDto> channels, String startDate, String endDate) {
        if(groupByType==null || channels==null || channels.size()==0 || startDate==null || endDate==null) {
            return null;
        }
        startDate = startDate.substring(0,10);
        endDate = endDate.substring(0,10);
        int days = DateUtils.compareDate(startDate,endDate,0);
        List<ChannelStatisticsChartDto> result = new ArrayList<>();
        if(days>=0) {
            for(ChannelStatisticsChartDto channelDto :channels) {
                if (groupByType.equals("hour")) {
                    for (int i = 0; i < 24; i++) {
                        String hour = i > 9 ? String.valueOf(i) : "0" + i;
                        result.add(initChannelStatisticsChartDto(channelDto.getId(), channelDto.getChannelName(), hour));
                    }
                } else if (groupByType.equals("day")) {
                    for (int i = 0; i <= days; i++) {
                        String date = DateUtils.addDayToDate(i, startDate, DateFormatUtils.DATE_FORMAT1);
                        date = date.replace("-", "/");
                        result.add(initChannelStatisticsChartDto(channelDto.getId(), channelDto.getChannelName(), date));
                    }
                } else if (groupByType.equals("month")) {
                    int monthNum = DateUtils.compareDate(startDate, endDate, 1) + 1;
                    for (int i = 0; i < monthNum; i++) {
                        String currentMonth = DateUtils.addMothToDate(i, startDate, DateFormatUtils.DATE_FORMAT1);
                        String yearMonth = currentMonth.replace("-", "/").substring(0, 7);
                        result.add(initChannelStatisticsChartDto(channelDto.getId(), channelDto.getChannelName(), yearMonth));
                    }
                }
            }
        }
        return result;
    }

    private ChannelStatisticsChartDto initChannelStatisticsChartDto(Long channelId, String channelName, String dateStr) {
        ChannelStatisticsChartDto dto = new ChannelStatisticsChartDto();
        dto.setId(channelId);
        dto.setChannelName(channelName);
        dto.setDateStr(dateStr);
        return dto;
    }

    /**
     * @api {get} /merchant/channel/statistics/detail 渠道详细数据
     * @apiGroup B端 merchant channel statistics
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {String} startDate 开始时间
     * @apiParam {String} endDate 结束时间
     * @apiParam {String} statisticsType YESTERDAY("昨天"), WEEK("最近一周"), MONTH("最近一个月"), QUATER("最近三个月")
     * @apiParam {Long} typeId 渠道类型ID
     *
     * @apiSuccess {String} typeName 渠道类型
     * @apiSuccess {String} channelName 渠道名称
     * @apiSuccess {String} merchantName 所有者
     * @apiSuccess {Long} categoryCount 上架产品种类
     * @apiSuccess {Long} viewCount 访问次数
     * @apiSuccess {Long} viewCustomer 访问人数
     * @apiSuccess {Long} saleCount 售出数
     * @apiSuccess {Long} saleCustomerCount 下单人数
     * @apiSuccess {Double} saleConversionRate 下单转化率
     * @apiSuccess {Long} verificationCount 核销数量
     * @apiSuccess {Long} verificationCustomerCount 核销人数
     * @apiSuccess {Double} verificationRate 核销转化率
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *     "data": [
     *       {
     *         "id": 130,
     *         "typeName": "网上店铺",
     *         "channelName": "新渠道",
     *         "viewCount": 0,
     *         "saleCount": 54,
     *         "saleCustomerCount": 3,
     *         "verificationCustomerCount": 0,
     *         "verificationCount": 0,
     *         "verificationRate": 0,
     *         "saleConversionRate": 0,
     *         "viewCustomer": 0
     *       }
     *     ],
     *     "totalCount": 1,
     *     "totalPage": 1,
     *     "pageNo": 0,
     *     "pageSize": 10
     *   }
     * }
     */
    @RequestMapping(value = Routes.MERCHANT_CHANNEL_STATISTICS_DETAIL, method = RequestMethod.GET)
    public JsonResult channelStatisticsDetail(ChannelStatisticsChartDto channelStatisticsChartDto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if(!checkDto(channelStatisticsChartDto,jsonResult)) {
                return;
            }
            Long cmallId = userInfoDto.mall.getId();
            Long cmerchantId = userInfoDto.merchant.getId();
            String startDate = channelStatisticsChartDto.getStartDate();
            String endDate = channelStatisticsChartDto.getEndDate();
            List<Long> typeIds = channelStatisticsChartDto.getTypeIds();
            String groupByType = channelStatisticsChartDto.getGroupByType();
            PageResult<ChannelStatisticsChartDto> pageResult = merchantChannelStatisticsService.findChannels(this.getPage(channelStatisticsChartDto.getPageNo(), channelStatisticsChartDto.getPageSize()),cmallId,cmerchantId,startDate,endDate,typeIds,null,null);
            if(pageResult.data !=null && pageResult.data.size()>0) {
                pageResult.data.forEach(dto -> {
                    Long channelId = dto.getId();
                    Long mallId = dto.getMallId();
                    Long merchantId = dto.getMerchantId();
                    Merchant merchant = merchantRepository.findOne(merchantId);
                    dto.setMerchantName(merchant.getName());
                    //上架产品种类数
                    Long cateCount = merchantChannelStatisticsService.computeChannelCategoryCount(mallId,merchantId,channelId);
                    cateCount=cateCount==null?0L:cateCount;
                    dto.setCategoryCount(cateCount);
                    //访问次数
                    Long viewCount = merchantChannelStatisticsService.channelViewCount(mallId,merchantId,startDate,endDate,typeIds,null,channelId);
                    viewCount = viewCount==null?0L:viewCount;
                    dto.setViewCount(viewCount);
                    //访客人数
                    Long viewCustomerCount = merchantChannelStatisticsService.channelViewCustomerCount(mallId,merchantId,startDate,endDate,typeIds,null,channelId);
                    viewCustomerCount = viewCustomerCount==null?0L:viewCustomerCount;
                    dto.setViewCustomer(viewCustomerCount);
                    //销售数量
                    Long saleCount = merchantChannelStatisticsService.channelSaleCount(mallId,merchantId,startDate,endDate,typeIds,null,channelId);
                    saleCount = saleCount==null?0L:saleCount;
                    dto.setSaleCount(saleCount);
                    //下单人数
                    Long orderCustomerCount = merchantChannelStatisticsService.channelOrderCustomerCount(mallId,merchantId,startDate,endDate,typeIds,null,channelId);
                    orderCustomerCount = orderCustomerCount==null?0L:orderCustomerCount;
                    dto.setSaleCustomerCount(orderCustomerCount);
                    Double saleRate = new Double(0);
                    if(viewCustomerCount!=null && viewCustomerCount.longValue()>0) {
                        saleRate=computeRate(orderCustomerCount,viewCustomerCount).doubleValue();
                    }
                    dto.setSaleConversionRate(saleRate);
                    //核销数量
                    Long verifyCount = merchantChannelStatisticsService.channelVerifyCount(mallId,merchantId,startDate,endDate,typeIds,null,channelId);
                    verifyCount = verifyCount==null?0L:verifyCount;
                    dto.setVerificationCount(verifyCount);
                    //核销人数
                    Long verifyCustomerCount = merchantChannelStatisticsService.channelVerifyCustomerCount(mallId,merchantId,startDate,endDate,typeIds,null,channelId);
                    verifyCustomerCount = verifyCustomerCount==null?0L:verifyCustomerCount;
                    dto.setVerificationCustomerCount(verifyCustomerCount);
                    Double verifyRate = new Double(0);
                    if(saleCount!=null && saleCount.longValue()>0) {
                        verifyRate = computeRate(verifyCount,saleCount).doubleValue();
                    }
                    dto.setVerificationRate(verifyRate);
                });
            }
            jsonResult.data = pageResult;
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /merchant/channel/statistics/product/detail 渠道-产品明细
     * @apiGroup B端 merchant channel statistics
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {Long} channelId 渠道ID
     * @apiParam {String} startDate 开始时间
     * @apiParam {String} endDate 结束时间
     * @apiParam {String} productSourceType ALL("全部"),SELF("自营"),MARKET("分销") 产品来源类型
     * @apiParam {String} type ALL("全部"),GOODS("商品"),SERVICE("服务") 类型
     * @apiParam {String} keyword 产品名称/编号
     *
     * @apiSuccess {String} productName 产品名称
     * @apiSuccess {Long} productId 产品编号
     * @apiSuccess {Long} salePrice 售价
     * @apiSuccess {Integer} clickCount 访问次数
     * @apiSuccess {Integer} visitorCount 访客人数
     * @apiSuccess {Long} orderCount 售出数量
     * @apiSuccess {Long} saleCustomerCount 下单人数
     * @apiSuccess {Long} verificationCustomerCount 核销人数
     * @apiSuccess {Long} verificationCount 核销数量
     * @apiSuccess {String} orderConversionRate 下单转化率
     * @apiSuccess {String} orderVerifiCationConversionRate 核销转化率
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *     "data": [
     *       {
     *         "productId": 936,
     *         "productSourceType": "SELF",
     *         "visitorCount": 14,
     *         "clickCount": 202,
     *         "orderCount": 20,
     *         "verificationCustomerCount": 0,
     *         "verificationCount": 0,
     *         "orderConversionRate": "21.43",
     *         "orderVerifiCationConversionRate": "0.00",
     *         "productName": "暗色蔚海 阔腿背带裤",
     *         "salePrice": 99,
     *         "saleCustomerCount": 3
     *       }
     *     ],
     *     "totalCount": 1,
     *     "totalPage": 1,
     *     "pageNo": 0,
     *     "pageSize": 10
     *   }
     * }
     *
     */
    @RequestMapping(value = Routes.MERCHANT_CHANNEL_STATISTICS_PRODUCTS_DETAIL, method = RequestMethod.GET)
    public JsonResult channelStatisticsProductDetail(MerchantProductStatisticsDto dto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            Long channelId = dto.getChannelId();
            if(channelId==null) {
                jsonResult.remind("渠道ID不能为空",log);
                return;
            }
            String productSourceType = dto.getProductSourceType();
            if (StringUtils.isNotBlank(productSourceType) && !EnumUtils.isValidEnum(MerchantOrderSourceType.class, productSourceType)) {
                jsonResult.remind("productSourceType 必须为ALL(\"全部\"), SELF(\"自营\"), MARKET(\"分销\")",log);
                return;
            }
            String type = dto.getType();
            if (StringUtils.isNotBlank(type) && !EnumUtils.isValidEnum(ProductType.class, type)) {
                jsonResult.remind("type 必须为 ALL(\"全部\"), GOODS(\"商品\"), SERVICE(\"服务\")",log);
                return;
            }
            if(StringUtils.isNotBlank(dto.getStartDate())) {
                dto.setStartDate(dto.getStartDate()+" 00:00:00");
            }
            if(StringUtils.isNotBlank(dto.getEndDate())) {
                dto.setEndDate(dto.getEndDate()+" 23:59:59");
            }
            Long cmallId = userInfoDto.mall.getId();
            Long cmerchantId = userInfoDto.merchant.getId();
            String startDate = dto.getStartDate();
            String endDate = dto.getEndDate();
            String keyword = dto.getKeyword();
            PageResult<MerchantProductStatisticsDto> pageResult = merchantProductStatisticsService.getProductStatisticsList(this.getPage(dto.getPageNo(),
                    dto.getPageSize()),cmallId,cmerchantId,null,productSourceType,type,startDate,endDate,keyword,channelId);
            if(pageResult.data !=null && pageResult.data.size()>0) {
                pageResult.data.forEach(productStatisticsDto -> {
                    Long productId = productStatisticsDto.getProductId();
                    Long mallId = productStatisticsDto.getMallId();
                    Long merchantId = productStatisticsDto.getMerchantId();
                    //访问次数
                    Long viewCount = merchantProductStatisticsService.getProductViewCount(mallId, merchantId, productId, productSourceType, type, startDate, endDate, channelId);
                    viewCount = viewCount == null ? 0L : viewCount;
                    productStatisticsDto.setClickCount(viewCount.intValue());
                    //访客人数
                    Long viewCustomerCount = merchantProductStatisticsService.getProductViewCustomerCount(mallId, merchantId, productId, productSourceType, type, startDate, endDate, channelId);
                    viewCustomerCount = viewCustomerCount == null ? 0L : viewCustomerCount;
                    productStatisticsDto.setVisitorCount(viewCustomerCount.intValue());
                    //售出数量
                    Long saleCount = merchantProductStatisticsService.getProductSalePayCount(mallId, merchantId, productId, productSourceType, type, startDate, endDate, channelId);
                    saleCount = saleCount == null ? 0L : saleCount;
                    productStatisticsDto.setOrderCount(saleCount);
                    //下单人数
                    Long saleCustomerCount = merchantProductStatisticsService.getProductSaleCustomerCount(mallId, merchantId, productId, productSourceType, type, startDate, endDate, channelId);
                    saleCustomerCount = saleCustomerCount == null ? 0L : saleCustomerCount;
                    productStatisticsDto.setSaleCustomerCount(saleCustomerCount);
                    //核销数量
                    Long verifyCount = merchantProductStatisticsService.getProductVerifyCount(mallId, merchantId, productId, productSourceType, type, startDate, endDate, channelId);
                    verifyCount = verifyCount == null ? 0L : verifyCount;
                    productStatisticsDto.setVerificationCount(verifyCount);
                    //核销人数
                    Long verifyCutomerCount = merchantProductStatisticsService.getProductVerifyCustomerCount(mallId, merchantId, productId, productSourceType, type, startDate, endDate, channelId);
                    verifyCutomerCount = verifyCutomerCount == null ? 0L : verifyCutomerCount;
                    productStatisticsDto.setVerificationCustomerCount(verifyCutomerCount);
                    //下单转化率
                    productStatisticsDto.setOrderConversionRate("0");
                    if(viewCustomerCount!=null && viewCustomerCount.longValue()>0) {
                        productStatisticsDto.setOrderConversionRate(String.valueOf(computeRate(saleCustomerCount,viewCustomerCount)));
                    }
                    //核销转化率
                    productStatisticsDto.setOrderVerifiCationConversionRate("0");
                    if(saleCount!=null && saleCount.longValue()>0) {
                        productStatisticsDto.setOrderVerifiCationConversionRate(String.valueOf(computeRate(verifyCount,saleCount)));
                    }
                });
            }
            jsonResult.data = pageResult;
        };
        return doing.go(request, log);
    }

    /**
     * 计算转化率
     * @param verifyCount
     * @param saleCount
     * @return
     */
    private BigDecimal computeRate(Long verifyCount, Long saleCount) {
        BigDecimal verifyCountBigDecimal = new BigDecimal(verifyCount);
        BigDecimal saleCountBigDecimal = new BigDecimal(saleCount);
        BigDecimal rate = verifyCountBigDecimal.divide(saleCountBigDecimal,4,BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
        return rate.setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    /**
     * 检查表单数据
     * @param dto
     * @param jsonResult
     */
    private boolean checkDto(ChannelStatisticsChartDto dto,JsonResult jsonResult) {
        String statisticsType = dto.getStatisticsType();
        if (StringUtils.isNotBlank(statisticsType) && !EnumUtils.isValidEnum(StatististicsType.class, statisticsType)) {
            jsonResult.remind("statisticsType 必须为 YESTERDAY(\"昨天\"), WEEK(\"最近一周\"), MONTH(\"最近一个月\"), QUATER(\"最近三个月\")",log);
            return false;
        }
        String startDate = dto.getStartDate();
        String endDate = dto.getEndDate();
        Long typeId = dto.getTypeId();
        //如果查询channelTypeId为一级 则将下级的channelTypeId加入列表
        List<Long> channelTypeIds = new ArrayList<>();
        if (typeId != null && typeId.longValue() > 0) {
            ChannelType channelType = channelTypeRepository.findOne(typeId);
            if (channelType == null) {
                jsonResult.remind("渠道类型ID不存在",log);
                return false;
            }
            if (channelType.getParentId() == null) {
                List<ChannelType> channelTypes = channelTypeRepository.findByParentIdAndIsDelete(typeId, Whether.NO);
                if (channelTypes != null && channelTypes.size() > 0) {
                    for (ChannelType ch : channelTypes) {
                        channelTypeIds.add(ch.getId());
                    }
                }
            } else {
                channelTypeIds.add(typeId);
            }
        }
        dto.setTypeIds(channelTypeIds);
        if (StringUtils.isNotBlank(statisticsType)) {
            Date today = DateUtils.getCurrentDate(DateFormatUtils.DATE_FORMAT1);
            //昨天
            if (StatististicsType.YESTERDAY == StatististicsType.valueOf(statisticsType)) {
                startDate = DateUtils.addDayToDate(-1,today,DateFormatUtils.DATE_FORMAT1);
                endDate = DateUtils.addDayToDate(-1,today,DateFormatUtils.DATE_FORMAT1);
            }
            //每周
            if (StatististicsType.WEEK == StatististicsType.valueOf(statisticsType)) {
                startDate = DateUtils.addDayToDate(-6, today,DateFormatUtils.DATE_FORMAT1);
                endDate = DateUtils.getCurrentTime(DateFormatUtils.DATE_FORMAT1);
            }
            //近一个月
            if (StatististicsType.MONTH == StatististicsType.valueOf(statisticsType)) {
                startDate = DateUtils.addMothToDate(-1,today,DateFormatUtils.DATE_FORMAT1);
                endDate = DateUtils.getCurrentTime(DateFormatUtils.DATE_FORMAT1);
            }
            //近三个月
            if (StatististicsType.QUATER == StatististicsType.valueOf(statisticsType)) {
                startDate = DateUtils.addMothToDate(-3,today,DateFormatUtils.DATE_FORMAT1);
                endDate = DateUtils.getCurrentTime(DateFormatUtils.DATE_FORMAT1);
            }
        }
        if(StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            dto.setGroupByType(computeInterval(startDate,endDate));
        }
        if(StringUtils.isNotBlank(startDate)) {
            dto.setStartDate(startDate+" 00:00:00");
        }
        if(StringUtils.isNotBlank(endDate)) {
            dto.setEndDate(endDate+" 23:59:59");
        }
        return true;
    }

    /**
     * 计算两个日期范围
     * @param startDate
     * @param endDate
     * @return
     */
    private String computeInterval(String startDate, String endDate) {
        String result = "";
        int days = DateUtils.compareDate(startDate,endDate,0);
        if(days==0) {
            result = "hour";
        } else if(days>0 && days<=31) {
            result = "day";
        } else if(days > 31) {
            result = "month";
        }
        return result;
    }

    /**
     * 获取渠道ID列表
     * @param channelList
     * @return
     */
    private List<Long> getChannelIds(List<ChannelStatisticsChartDto> channelList) {
        List<Long> ids = null;
        if(channelList!=null && channelList.size()>0) {
            ids = new ArrayList<>();
            for(ChannelStatisticsChartDto dto : channelList) {
                if(dto.getId()!=null && dto.getId().longValue()>0) {
                    ids.add(dto.getId());
                }
            }
        }
        return ids;
    }

    /**
     * 计算转化率
     * @param numerator
     * @param denominator
     * @return
     */
    private List<ChannelStatisticsChartDto> calConversionRate(List<ChannelStatisticsChartDto> numerator,List<ChannelStatisticsChartDto> denominator, String keyRate) {
        Set dateSet = new HashSet<>();
        List<ChannelStatisticsChartDto> resultList=null;
        createDateSet(numerator,dateSet);
        createDateSet(denominator,dateSet);
        if(dateSet.size()>0) {
            resultList = new ArrayList<>();
            Iterator it=dateSet.iterator();
            while(it.hasNext()) {
                String date = (String) it.next();
                ChannelStatisticsChartDto firstDto = findDtoByDate(date,numerator);
                ChannelStatisticsChartDto secondDto = findDtoByDate(date,denominator);
                ChannelStatisticsChartDto dto = new ChannelStatisticsChartDto();
                if(firstDto!=null && secondDto!=null) {
                    BigDecimal numeratorBigDecimal = null;
                    BigDecimal denominatorBigDecimal = null;
                    if(keyRate.equals("sale")) {
                        numeratorBigDecimal = new BigDecimal(firstDto.getSaleCustomerCount());
                        denominatorBigDecimal = new BigDecimal(secondDto.getViewCustomer());
                        if(secondDto.getViewCustomer().longValue()!=0) {
                            BigDecimal rate = numeratorBigDecimal.divide(denominatorBigDecimal, 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
                            dto.setSaleConversionRate(rate.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                        } else {
                            dto.setSaleConversionRate(new Double(0));
                        }
                    } else if(keyRate.equals("verification")) {
                        numeratorBigDecimal = new BigDecimal(firstDto.getVerificationCount());
                        denominatorBigDecimal = new BigDecimal(secondDto.getSaleCount());
                        if(secondDto.getSaleCount().longValue()!=0) {
                            BigDecimal rate = numeratorBigDecimal.divide(denominatorBigDecimal, 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
                            dto.setVerificationRate(rate.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                        } else {
                            dto.setVerificationRate(new Double(0));
                        }
                    }
                    dto.setId(firstDto.getId());
                    dto.setDateStr(firstDto.getDateStr());
                    dto.setChannelName(firstDto.getChannelName());
                } else {
                    if(keyRate.equals("sale")) {
                        dto.setSaleConversionRate(new Double(0));
                    } else if(keyRate.equals("verification")) {
                        dto.setVerificationRate(new Double(0));
                    }
                    String name = firstDto==null?(secondDto==null?"":secondDto.getChannelName()):firstDto.getChannelName();
                    String dateStr = firstDto==null?(secondDto==null?"":secondDto.getDateStr()):firstDto.getDateStr();
                    Long id = firstDto==null?(secondDto==null?null:secondDto.getId()):firstDto.getId();
                    dto.setDateStr(dateStr);
                    dto.setChannelName(name);
                    dto.setId(id);
                }
                resultList.add(dto);
            }
        }
        return resultList;
    }

    /**
     * 查询对应日期数据
     * @param dateStr
     * @param list
     * @return
     */
    private ChannelStatisticsChartDto findDtoByDate(String dateStr,List<ChannelStatisticsChartDto> list) {
        ChannelStatisticsChartDto dto = null;
        if(list!=null && list.size()>0) {
            for(ChannelStatisticsChartDto p:list) {
                if(dateStr.equals(p.getDateStr()+"-"+p.getId())) {
                    return p;
                }
            }
        }
        return dto;
    }

    /**
     * 添加日期到集合
     * @param list
     * @param dateSet
     */
    private void createDateSet(List<ChannelStatisticsChartDto> list,Set dateSet) {
        if(list!=null && list.size()>0) {
            for(ChannelStatisticsChartDto dto:list) {
                dateSet.add(dto.getDateStr()+"-"+dto.getId());
            }
        }
    }
}
